<?php

namespace App\Services\My;


use App\Constants\CodeData;
use App\Dao\AnchorVideoDao;
use App\Dao\AppUpgradeDao;
use App\Dao\EventDao;
use App\Dao\GiftDao;
use App\Dao\PayCallDao;
use App\Dao\PhotoDao;
use App\Dao\TopicDao;
use App\Exception\MessageException;
use App\Model\Anchor;
use App\Model\AnchorEvaluate;
use App\Model\AnchorVideo;
use App\Model\User;
use App\Model\UserCardPack;
use App\Model\VisitList;
use App\Services\Sms\SmsService;
use App\Services\User\UserService;
use App\Utils\MemcacheClient;
use Hyperf\DbConnection\Db;

class MyService
{

    /**
     * Note - 用户背包
     * DateTime 2024/8/8 15:22
     * User Admin
     * @param $userInfo
     * @param $cardType - 1-音视频体验卡;2-微信加速卡;3-vip体验卡
     * @param $language
     */
    public function backpack($userInfo, $cardType, $language)
    {
        $uid = $userInfo['id'];
        // $data = $userModel->findAll("id,uid,card_type,get_time,status", "uid=? and status=? {$where}", [$uid, 0], "get_time desc", "", "tb_user_card_pack");
        $data = UserCardPack::query()->select('id', 'uid', 'card_type', 'get_time', 'status')
            ->when($cardType > 0, function ($query) use ($cardType) {
                $query->where('card_type', $cardType);
            })
            ->where('uid', $uid)
            ->where('status', 0)
            ->orderBy('get_time', 'desc')->get()->toArray();
        $can_use = 0;
        if ($userInfo['sex'] == 1) {
            $times = strtotime(date("Ymd"));
            $noExist = UserCardPack::query()
                ->when($cardType > 0, function ($query) use ($cardType) {
                    $query->where('card_type', $cardType);
                })
                ->where('uid', $uid)
                ->where('status', 1)
                ->where('use_time', '>', $times)
                ->doesntExist();
            if ($noExist) {
                $can_use = 1;
            }

            if ($language == 'zh-hk') {
                $rule = "<p>體驗卡獲取規則：</p><p>體驗卡：可透過新人活動領取，同時召回老用戶也能獲得體驗卡</p><p>加速卡：通過新人活動領取</p><p>音頻視頻體驗卡：</p><p>用於與用戶的首次通話體驗；此卡可讓您免費與對方通話60秒</p>";
            } elseif ($language == 'zh-cn') {
                $rule = "<p>体验卡获得规则：</p><p>体验卡：可通过新人活动领取、老用户召回也可获得体验卡</p><p>加速卡：通过新人活动领取</p><p>音视频体验卡：</p><p>用于跟用户首次通话体验；该卡可免费跟对方通话60s</p>";
            } else {
                $rule = "<p>Experience Card Acquisition Rules:</p><p>Experience Card: Can be obtained through the newbie activity, and can also be obtained by recalling the old user</p><p>Acceleration Card: Obtained through the newbie activity</p><p>Video Call Experience Card:</p><p>Used for the first call experience with the user; This card can be used to call the user for free for 60 seconds</p>";
            }
        } else {
            if ($language == 'zh-hk') {
                $rule = "<p>體驗卡獲取規則：新男性用戶當天首次主動致電给您進行視頻通話，可獲得一張體驗卡，體驗卡可兌換成積分，一張卡=1積分。</p><p>體驗卡兌換規則：</p><p>1、點擊立即兌換僅兌換當前體驗卡+1積分。</p><p>2、選擇一鍵兌換直接兌換全部通話券，積分是所有券的總和。</p>";
            } elseif ($language == 'zh-cn') {
                $rule = "<p>体验卡获得规则：新人男用户当天首次主动给您拨打视频通话，可获得一张体验卡，体验卡可兑换成积分，一张卡=1积分。</p><p>体验卡兑换规则：</p><p>1、点击立即兑换只兑换当前体验卡+1积分。</p><p>2、选择一键兑换直接兑换全部通话券，积分是所有券的总和。</p>";
            } else {
                $rule = "<p>Experience Card Acquisition Rules: New male users who initiate a video call with you for the first time on the same day will earn an experience card. These cards can be exchanged for points, with one card equaling 1 point.</p><p>Experience Card Redemption Rules:</p><p>1、Clicking on 'Redeem Now' will only redeem the current experience card for +1 point.</p><p>2、Selecting 'One-click Redemption' will directly redeem all call vouchers, with the points totaling the sum of all vouchers.</p>";
            }
        }

        foreach ($data as &$ite) {
            if ($ite['card_type'] == 1) {
                $ite['can_use'] = (string)$can_use;
                if ($can_use == 1) {
                    $can_use = 0;
                }
            }
            $ite['get_time'] = date("Y-m-d H:i:s", $ite['get_time']);
        }

        // Tool::JSON(\CodeData::SUCCESS, ['result' => 1, 'msg' => ['rules' => $rule, 'card_list' => $data]], 'success');
        return formatData(['msg' => ['rules' => $rule, 'card_list' => $data], 'result' => 1]);
    }

    /**
     * Note - 送礼收礼数据
     * DateTime 2024/8/8 15:26
     * User Admin
     * @param $userInfo
     * @param $userId
     * @return array
     */
    public function receiveOrGiveGift($userInfo, $userId)
    {
        $uid = $userInfo['id'];
        $giftDao = GiftDao::getInstance();
        if (!empty($userId)) {
            // 查看其他用户的收礼送礼情况
            $sex = User::query()->where('id', $userId)->value('sex');
            if ($sex == 2) {
                // 主播查看收礼数据
                $gift = $giftDao->getGiftByUid($userId, 2);
            } else {
                // 男用户查看送礼数据
                $gift = $giftDao->getGiftByUid($userId, 1);
            }
        } else {
            // 查看自己的收礼送礼情况（个人中心照片墙）
            if ($userInfo['sex'] == 2) {
                // 主播查看自己收礼数据
                $gift = $giftDao->getGiftByUid($uid, 2);
            } else {
                // 男用户查看自己送礼数据
                $gift = $giftDao->getGiftByUid($uid, 1);
            }
        }

        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1,'msg'=>$gift), 'success');
        return formatData(['msg' => $gift, 'result' => 1]);

    }


    /**
     * Note - 个人中心数据
     * DateTime 2024/8/9 11:53
     * User Admin
     * @param mixed $userInfo
     * @param $params
     * @return array
     */
    public function myInfo(mixed $userInfo, $params)
    {
        $uid = $userInfo['id'];
        // 添加用户首次进入app首页的时间
        if (!$userInfo['first_in_app_time'] > 0) {
            $time = time();
            if ($time - $userInfo['register_time'] > 24 * 3600) {
                $time = $userInfo['register_time'];
            }
            $userInfo['first_in_app_time'] = $time;
            if ($userInfo['sex'] == 2) {
                $userInfo['push_level'] = empty($userInfo['guild_num']) ? 1 : 2;
                User::query()->where('id', $uid)->update(['first_in_app_time' => $time, 'push_level' => 2]);
            } else {
                $userInfo['push_level'] = 1;
                User::query()->where('id', $uid)->update(['first_in_app_time' => $time, 'push_level' => 1]);
            }
        }
        return (new UserService())->getUserInfo($userInfo, $params);

    }


    /**
     * Note - 我的-视频管理接口（增删改）没有查
     * DateTime 2024/8/9 11:53
     * User Admin
     * @param mixed $userInfo
     * @param array $params
     * @return array
     */
    public function videoAction(mixed $userInfo, array $params)
    {
        $uid = $userInfo['id'];
        $id = $params['id'] ?? '';
        $action = $params['action'];
        $first_photo = $params['first_photo'];
        $title = $params['title'] ?? '';
        $video_url = $params['video_url'] ?? '';
        $is_recommend = $params['is_recommend'] ?? 0;//0公开 1vip可见
        switch ($action) {
            case 'insert':
                return AnchorVideoDao::getInstance()->insert($uid, $first_photo, $title, $video_url, $is_recommend);
            case 'delete':
                return AnchorVideoDao::getInstance()->delete($uid, $id);
            case 'update':
                return AnchorVideoDao::getInstance()->update($id, $uid, $is_recommend);
            default:
                return formatData([], 200, CodeData::NEED_TIPS, '参数错误');
        }

    }


    /**
     * Note - 我的-照片管理接口（增删改查）
     * DateTime 2024/8/9 15:46
     * User Admin
     * @param mixed $userInfo
     * @param array $params
     */
    public function photoAction(mixed $userInfo, array $params)
    {
        $uid = $userInfo['id'];
        $action = $params['action'];
        // 0-公开展示 1-vip可见;
        $is_recommend = $params['show_type'] ?? 0;
        $image_url = $params['image_url'] ?? '';
        $id = $params['id'] ?? '';

        return match ($action) {
            'insert' => PhotoDao::getInstance()->insert($uid, 1, $is_recommend, $image_url),
            'update' => PhotoDao::getInstance()->update($uid, $id, $is_recommend),
            'delete' => PhotoDao::getInstance()->delete($uid, $id),
            'view' => PhotoDao::getInstance()->view($uid),
            default => [],
        };
    }


    /**
     * Note - 未读消息数量
     * DateTime 2024/8/15 11:41
     * User Admin
     * @param mixed $userInfo
     * @param $params
     * @return array
     */
    public function unreadMessageNum(mixed $userInfo, $params)
    {
        $uid = $userInfo['id'];
        $login_env = (new AppUpgradeDao())->isHideMaleChatCost(1, $params['version_code'], $params['channel'], $userInfo['last_login_ip'], $uid);
        // 活动消息未读数
        $data['event_num'] = $login_env ? 0 : EventDao::getInstance()->notReadNum($userInfo);

        // 通话记录未读数
        $where[] = ['id', '>', 0];
        $where[] = ['is_read', '=', 0];
        if ($userInfo['sex'] == 1) {  //男
            $where[] = ['user_id', '=', $uid];
            $where[] = ['caller', '=', 2];

        } else {
            $where[] = ['anchor_id', '=', $uid];
            $where[] = ['caller', '=', 1];
        }
        $data['pay_call_num'] = $login_env ? 0 : PayCallDao::getInstance()->notReadNum($where);


        // 视频/动态 通知消息
        $data['topic_num'] = $login_env ? 0 : TopicDao::getInstance()->notReadNum($uid);

        // 访客数量
        // $followModel = new Follow2Model();
        $data['visitor_num'] = $login_env ? 0 : VisitList::getNotReadVisitCount($uid);
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $data), 'success！');
        return formatData(['result' => 1, 'msg' => $data]);
    }


    /**
     * Note - 绑定手机号
     * DateTime 2024/8/15 11:41
     * User Admin
     * @param $uid
     * @param array $params
     * @return array
     */
    public function bindPhone($uid, array $params)
    {
        $account = $params['account'];
        $code = $params['code'];
        if (!User::checkPhone($account)) {
            SmsService::validateCode($account, $code);
            User::query()->where('id', $uid)->update(['phone' => $account, 'is_binding' => 1]);
            $memcache = MemcacheClient::getInstance();
            $memcache->delete("anchorInfo_" . $uid);
            $memcache->delete("userInfo_" . $uid);
            $memcache->delete('user_identity_info_' . $uid);
            return formatData(['result' => 1], 200, CodeData::SUCCESS, '绑定成功');
        } else {
            throw new MessageException('已被使用');
        }

    }

    /**
     * Note - 绑定支付宝
     * DateTime 2024/8/15 11:41
     * User Admin
     * @param $uid
     * @param array $params
     * @return array
     */
    public function bindAlipay($uid, array $params)
    {
        $account = $params['account'];
        if (!Anchor::checkAliPay($account)) {
            Anchor::query()->where('uid', $uid)->update(['alipay_id' => $account]);
            $memcache = MemcacheClient::getInstance();
            $memcache->delete("anchorInfo_" . $uid);
            $memcache->delete("userInfo_" . $uid);
            $memcache->delete('user_identity_info_' . $uid);
            return formatData(['result' => 1], 200, CodeData::SUCCESS, '绑定成功');
        } else {
            throw new MessageException('已被使用');
        }
    }


    /**
     * Note - 修改密码
     * DateTime 2024/8/15 12:57
     * User Admin
     * @param $uid
     * @param $password
     */
    public function setPassword($uid, $password)
    {
        $update = ['password' => md5($password . PASS_SALT)];
        $re = User::query()->where('id', $uid)->update($update);
        if ($re) {
            // \Tool::JSON(\CodeData::SUCCESS, array('result' => 1), '密码设置成功');
            return formatData(['result' => 1], 200, CodeData::SUCCESS, '设置成功');
        }
        throw new MessageException('修改失败');
    }


    /**
     * Note - 修改或重置
     * DateTime 2024/8/15 12:57
     * User Admin
     * @param array $params
     * @return array|void
     */
    public function modifyOrResetPassword(array $params)
    {
        $account = $params['account'];
        $code = $params['code'];
        $password = $params['password'];
        $exists = User::query()->where('phone', $account)->exists();
        if ($exists) {
            SmsService::validateCode($account, $code);
            $update = ['password' => md5($password . PASS_SALT)];
            $re = User::query()->where('phone', $account)->update($update);
            if ($re) {
                // \Tool::JSON(\CodeData::SUCCESS, array('result' => 1), '密码设置成功');
                return formatData(['result' => 1], 200, CodeData::SUCCESS, '修改成功');
            }
        } else {
            throw new MessageException('用户不存在');
        }

    }

    /**
     * Note - 头像修改
     * DateTime 2024/9/3 16:04
     * User Admin
     * @param mixed $uid
     * @param mixed $image_url
     * @return array
     */
    public function headImageEdit(mixed $uid, mixed $image_url)
    {
        $data['isNewAudit'] = 0;  //非初审
        $data['head_image_new'] = $image_url;
        $data['head_image_status'] = 3;  //1-待审核；2-审核不通过；3-审核通过
        $data['head_image'] = $image_url; // 直接审核通过了
        $data['head_image_time'] = time();
        // $userModel = new UserModel();
        // $retval = $userModel->updateV2($uid, $data);
        $ret = User::where('id', $uid)->update($data);
        if ($ret) {
            MemcacheClient::getInstance()->delete("userInfo_" . $uid);
            // $user = UserDao::getInstance()->findUserInfoCache($uid);
            // $retval = array('result' => 1, 'msg' => $user);
            // Tool::JSON(\CodeData::SUCCESS, $retval, '头像上传成功');
            $retVal = array('result' => 1, 'msg' => [
                'head_image' => $image_url,
                'head_image_new' => $image_url,
                'head_image_status' => 3
            ]);
            return formatData($retVal);
        } else {
            // Tool::JSON(\CodeData::NEED_TIPS, '', '上传失败');
            throw new MessageException('上传失败');
        }
    }

    /**
     * Note - 设置用户喜欢的标签
     * DateTime 2024/9/3 16:04
     * User Admin
     * @param $userInfo
     * @param $ids
     * @return array
     */
    public function wantEvaluate($userInfo, $ids)
    {
        if ($userInfo['sex'] == 2) {
            throw new MessageException('仅限男用户设置');
        }

        if (!empty($ids)) {
            $ids = str_replace('，', ',', $ids);
            $idArr = explode(",", $ids);
            $counte = AnchorEvaluate::query()->whereIn('id', $idArr)->count();
            if (count($idArr) != $counte) {
                throw new MessageException("标签选择错误！");
            }
        }
        User::query()->where('id', $userInfo['id'])->update(['want_evaluate' => $ids]);
        return formatData(['result' => 1]);
    }
}